package com.hxrfid.web.controller.system.openApi;


import cn.hutool.core.util.ObjectUtil;
import com.hxrfid.common.core.controller.BaseController;
import com.hxrfid.common.core.domain.R;
import com.hxrfid.common.exception.ServiceException;
import com.hxrfid.project.service.IBsOrderService;
import com.hxrfid.system.domain.SysOss;
import com.hxrfid.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 开放接口
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/open/api")
public class OpenApiController extends BaseController {

    private final ISysOssService iSysOssService;
    private final IBsOrderService iBsOrderService;

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOss oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    /**
     * 微信支付回调通知
     * @param request 请求对象
     * @return 回调响应
     */
    @PostMapping("/wxPayNotify")
    public ResponseEntity<String> wxPayNotify(HttpServletRequest request) {
        try {
            String result = iBsOrderService.handleWxPayNotify(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500)
                .body("{\"code\":\"FAIL\",\"message\":\"失败\"}");
        }
    }

}
